﻿<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.IO;
using System.Net;
using System.Web;

public class UploadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            if (!string.IsNullOrEmpty(context.Request.Params["a"]))
            {
                switch (context.Request.Params["a"].Trim())
                {
                    case "check":
                        Check(context);
                        break;
                    case "upload":
                        context.Response.ContentType = "application/json";
                        Upload(context);
                        break;
                    default:

                        break;
                }
            }
        }
        catch (Exception ex)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(ex.Message);
        }
    }

    private void Check(HttpContext context)
    {
        string strUploadPath =
                context.Request.PhysicalApplicationPath +
                context.Request.Params["folder"].Trim('/').Replace("/", "\\") + "\\";

        string[] checkList = new string[] { };

        for (int i = 0; i < context.Request.Files.Count; i++)
        {
            HttpPostedFile postedFile = context.Request.Files[i];
            if (File.Exists(strUploadPath + Path.GetFileName(postedFile.FileName)))
            {
                checkList[i] = Path.GetFileName(postedFile.FileName);
            }
        }
        context.Response.Write(TQB.Common.Javascript.JSONSerializer.ToJSON(checkList));
    }

    private void Upload(HttpContext context)
    {
        string[] fileArray = new string[] { "ok" };

        for (int i = 0; i < context.Request.Files.Count; i++)
        {
            fileArray[i] = TQBFiles.UploadFile(context.Request.Files[i], context.Request.Params["folder"], true);
        }

        context.Response.Write(TQB.Common.Javascript.JSONSerializer.ToJSON(fileArray));

    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}